/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {StyleSheet, Text, View, ListView, RefreshControl, PixelRatio, Dimensions, TouchableOpacity, TouchableWithoutFeedback, DeviceEventEmitter, TouchableHighlight, Image, ScrollView, Platform, BackHandler} from 'react-native';

import Swiper from 'react-native-swiper';

import Carousel from '../../component/carousel';

import {CachedImage, CachedImageBackground} from "react-native-img-cache";

import Common from '../../component/common';

import ToolbarComponent from '../../component/ToolbarComponent';

import Loading from '../../component/loading';

import LoadError from '../../component/loadError';

import BriefIntroduction from './briefIntroduction';

import ColumnDetails from './columnDetails';

import Subscribe from './subscribe';

import Login from '../me/login';

const totalWidth = Dimensions.get('window').width;

const os = Platform.OS;

export default class Index extends Component {
  constructor(props) {
    super(props);
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      isRefreshing: false,
      expertList: ds,
      loading: true,
      success: false,
      errorMessage: '',
      np: 1,
      pageSize:20,
      noMoreData:false,
      checkDevice: '',
      slider1ActiveSlide: 0,
    };
    this.swiper = [];
    this.expertList = [];
  }

  componentWillMount(){
    Common.checkDevice((checkDevice) => {
      this.setState({checkDevice});
    });
    if (os === 'android') {  
      BackHandler.addEventListener('hardwareBackPress',() => Common.onBack(this));  
    }
    this.specialColumnIndex = DeviceEventEmitter.addListener('successPay',()=>{
      this.fetchSpecialColumnData();
    });
    this.loginStatus = DeviceEventEmitter.addListener('loginStatus',()=>{
      this.fetchSpecialColumnData();
    });
  }
  componentDidMount(){
    this.fetchSpecialColumnData();
  }
  componentWillUnmount() {
    this.specialColumnIndex.remove();
    this.loginStatus.remove();
    if (os === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));  
    }
  }
  fetchSpecialColumnData = () => {
    this.setState({
      loading: true,
      success: false,
      loadingMoreData: false
    });
    let formData = new FormData();
    if(typeof loginInfo != 'undefined' && loginInfo){
      formData.append('userToken',loginInfo.userToken);
    }
    Common.fetchData("post", '/specialColumn/list',formData,(resp) => {
      var responseData = Common.page("listResult",resp);
      this.swiper = resp.carouselResult;
      this.expertList = responseData.result;
      this.setState({expertList: this.state.expertList.cloneWithRows(this.expertList),
                      pageSize: responseData.pageSize,
                      np: responseData.np+1,
                      ap: responseData.ap,
                      noMoreData: responseData.noMoreData,
                      loading: false,
                      success: true,
                      loadingMoreData: true
                    });
      },() => {
        this.setState({loading: false,
                        success: false,
                        errorMessage: "请求失败",
                        loadingMoreData: true
                      });
      },() => {
        this.setState({loading: false,
                        success: false,
                        errorMessage: "网络错误",
                        loadingMoreData: true
                      });
      });
  };
  fetchPage = () => {
    let params = {
      "nowpage": this.state.np,
      "pagesize":this.state.pageSize,
      'userToken':typeof loginInfo != 'undefined' && loginInfo?loginInfo.userToken:""
    }
    Common.paging(params, '/specialColumn/list',(resp) => {
      var responseData = Common.page("listResult", resp);
      if(this.state.np == 1){
        this.swiper = resp.carouselResult;
      }
      this.expertList = this.expertList.concat(responseData.result);
      this.setState({
        expertList: this.state.expertList.cloneWithRows(this.expertList),
        np:responseData.np+1,
        ap:responseData.ap,
        noMoreData:responseData.noMoreData,
        loading: false,
        success: true,
        loadingFail:false,
        loadingMoreData:true,
      })
    },() => {
      if(this.state.np===1){
        this.setState({
          loading: false,
          success: false,
          errorMessage: "请求失败",
          loadingMoreData:true,
        })
      }else{
        this.setState({
          loadingFail: true,
          loadingFailText:"加载失败，点我重新加载",
          loadingMoreData:true,
        })
      }
    },() => {
      if(this.state.np===1){
        this.setState({
          loading: false,
          success: false,
          errorMessage: "网络错误",
          loadingMoreData:true,
        })
      }else{
        this.setState({
          loadingFail: true,
          loadingFailText:"加载失败，点我重新加载",
          loadingMoreData:true,
        })
      }
    });
  }
  _onRefresh = () => {
    this.setState({isRefreshing: true,loadingMoreData: false});
    let formData = new FormData();
    if(typeof loginInfo != 'undefined' && loginInfo){
      formData.append('userToken',loginInfo.userToken);
    }
    Common.fetchData("post", '/specialColumn/list',formData,(resp) => {
      var responseData = Common.page("listResult",resp);
      this.swiper = resp.carouselResult;
      this.expertList = responseData.result;
      this.setState({expertList: this.state.expertList.cloneWithRows(this.expertList),
                      pageSize: responseData.pageSize,
                      np: responseData.np+1,
                      ap: responseData.ap,
                      noMoreData: responseData.noMoreData,
                      isRefreshing: false,
                      success: true,
                      loadingMoreData: true
                    });
      },() => {
        this.setState({isRefreshing: false,
                        success: false,
                        errorMessage: "请求失败",
                        loadingMoreData: true
                      });
      },() => {
        this.setState({isRefreshing: false,
                        success: false,
                        errorMessage: "网络错误",
                        loadingMoreData: true
                      });
      });
  };
  orderBuy = (id) =>{
    if(typeof loginInfo != 'undefined' && loginInfo){
      Common.onForward(this, Subscribe, 8, id);
    }else{
      Common.onForward(this, Login);
    }
  };
  goPage = (info) => {
    if(info.type){
      switch (info.type){
        case 8 :
          Common.onForward(this, BriefIntroduction, "", info.id);
          break;
        case 9 :
          Common.onForward(this, ColumnDetails, info.title, info.id);
          break;
      }
    }
  };
  loadingMoreData = () =>{
    if(!this.state.noMoreData && this.state.loadingMoreData){
      this.fetchPage();
      
    }
  };
  refreshData = () =>{
    this.setState({
      loadingFailText:"加载中...."
    })
    this.loadingAgain = setTimeout(() => {
      this.fetchPage();
      clearTimeout(this.loadingAgain);
    },1000)
  };

  _renderItemWithParallax =(item, index) => {
    return (
      <View style={{height: totalWidth*0.49,marginTop: 10}}>
        <CachedImage source={{ uri: item.mainPicPath }} style={{...StyleSheet.absoluteFillObject, borderRadius: 5}} />
      </View>
    );
  };
  renderHeader = () => {
    return (
      <Carousel
        height={totalWidth*0.49+10}
        autoplay={true}
        interval={4000}
        data={this.swiper}
        contentRender={(item,index) => this._renderItemWithParallax(item,index)}
        onPress={(item) => this.goPage(item)}
      />
    )
  };
  renderListFooter = () => {
    return(
      <View>
        {
        this.state.noMoreData ? <View style={styles.noMoreData}><Text style={styles.noMoreDataText}>数据已全部加载完毕</Text></View>:null
      }
      {
        this.state.loadingFail ? <TouchableOpacity onPress = {this.refreshData} style={styles.noMoreData}><Text style={styles.noMoreDataText}>{this.state.loadingFailText}</Text></TouchableOpacity>:null
      }
    </View>
    )
  }
  renderRow = (rowData) => {
    var icon = "";
    if(rowData.isNew){
      icon = require('../../images/specialColumn/NEW.png');
    }
    if(rowData.isBuy){
      icon = require('../../images/specialColumn/yidingyue.png');
    }
    var ding = require('../../images/specialColumn/ding.png');
    return(
      <TouchableHighlight style={styles.specialColumnItemTouch} underlayColor="#fafafa" delayPressIn={100} onPress={() => Common.onForward(this,BriefIntroduction,"",rowData.id)}>
        <View style={styles.specialColumnItem}>
          <View style={styles.specialColumnItemLeft}>
            <View style={styles.specialColumnUser} >
              {rowData.userPic?
                <CachedImageBackground style={styles.userImg} source={{uri: rowData.userPic}} />:
                <Image style={styles.userImg} source={require('../../images/me/User.png')} />
              }
              <View style={styles.userInfo}>
                <Text style={styles.userName}>{rowData.userName}</Text>
                <Text style={styles.userntroduce}>{rowData.userRank}</Text>
              </View>
            </View>
            <View style={styles.specialBox}>
              <Text style={styles.specialTitle} numberOfLines={2}>{rowData.specialColumnTitle}</Text>
              <Text style={styles.specialCon} numberOfLines={3}>{rowData.specialColumnSubject}</Text>
              {
                rowData.isBuy?null:
                <View style={styles.specialPrice}>
                  <Text style={styles.specialMoney}>{rowData.totalColumnMoney}元</Text>
                  <TouchableOpacity style={{padding: 3,marginLeft: 5}} onPress={() => this.orderBuy(rowData.id)}>
                    <Image style={{width: totalWidth*0.033,height: totalWidth*0.033,resizeMode: 'contain'}} source={ding} />
                  </TouchableOpacity>
                </View>
              }
            </View>
          </View>
          <View style={styles.specialColumnItemRight}>
          {rowData.specialColumnPic1?
            <CachedImageBackground style={styles.coverImg} source={{uri: rowData.specialColumnPic1}}/>:
            <View style={[styles.coverImg,{borderColor: '#ededed', borderWidth: 1}]}>
              <Text style={{color: '#ededed',fontSize: 12}}>暂无图片</Text>
            </View>
          }
          </View>
          {icon?
            <Image style={styles.coverIcon} source={icon} />:null
          }
        </View>
      </TouchableHighlight>
    )
  };
  render() {
    return (
      <View style={{flex: 1}}>
        {/*标题行*/}
        <ToolbarComponent>
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT}>专栏</Text>
          </View>
        </ToolbarComponent>
        {
        this.state.loading?
          <Loading />:
          (this.state.success?
            <ListView
              style={[styles.container,this.state.checkDevice == 'x'?{marginBottom:totalWidth*0.07}:null]}
              refreshControl={
                <RefreshControl
                  refreshing={this.state.isRefreshing}
                  onRefresh={this._onRefresh}
                  />
                }
              dataSource={this.state.expertList}
              renderHeader={this.renderHeader}
              renderFooter = {this.renderListFooter}
              renderRow={this.renderRow}
              stickySectionHeadersEnabled={true}
              enableEmptySections={true}
              directionalLockEnabled={true}
              removeClippedSubviews={false}
              onEndReached={this.loadingMoreData}
              onEndReachedThreshold={500}
            />:<LoadError reload={this.fetchSpecialColumnData} reason={this.state.errorMessage}/>
          ) 
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f0f0f0',
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 20
  },
  slider: {
      marginTop: 5,
      overflow: 'visible' // for custom animations
  },
  sliderContentContainer: {
      paddingVertical: 5 // for custom animation
  },
  bgimg: {
    width: totalWidth,
    height: totalWidth*0.55,
    marginBottom: totalWidth*0.039,
  },
  specialColumnItemTouch:{
    backgroundColor: '#ffffff',
    marginTop: totalWidth*0.03,
    marginHorizontal: 5,
    borderRadius: 5
  },
  specialColumnItem: {
    flexDirection: 'row',
    padding: totalWidth*0.038,
    paddingLeft: totalWidth*0.058,
  },
  specialColumnItemLeft: {
    flex: 2,
  },
  specialColumnUser: {
    paddingTop: totalWidth*0.004,
    paddingBottom: totalWidth*0.029,
    flexDirection: 'row',
    alignItems: 'flex-start',
  },
  userImg: {
    width: totalWidth*0.1,
    height: totalWidth*0.1,
    borderRadius: totalWidth*0.05,
    marginRight: totalWidth*0.02,
  },
  userInfo: {
    flex: 1,
  },
  userName: {
    color: '#000',
    fontSize: 12,
    lineHeight: Math.round(totalWidth*0.056),
  },
  userntroduce: {
    color: '#939393',
    fontSize: 11,
    lineHeight: Math.round(totalWidth*0.04),
  },
  specialBox: {
    borderTopWidth: 1/PixelRatio.get(),
    borderColor: '#d2d2d2'
  },
  specialTitle: {
    color: '#000',
    fontSize: 17,
    marginVertical: totalWidth*0.02,
  },
  specialCon: {
    color: '#949494',
    fontSize: 11,
    lineHeight: Math.round(totalWidth*0.04),
  },
  specialPrice: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: totalWidth*0.02,
  },
  specialMoney: {
    color: '#fdad3a',
    fontSize: 12,
  },
  specialColumnItemRight: {
    flex: 1,
    alignItems: 'flex-end'
  },
  coverImg: {
    width: totalWidth*0.243,
    height: totalWidth*0.328,
    justifyContent: 'center',
    alignItems: 'center',
  },
  coverIcon: {
    position: 'absolute',
    top: 0,
    right: totalWidth*0.038,
  },
  noMoreData:{
    flex:1,
    justifyContent:"center",
    alignItems:"center",
    height:totalWidth*0.1,
    flexDirection:"row",
  },
  noMoreDataText:{
    fontSize:12,
  }
});